/**
 *  学习目标：Todos 案例
 */
import React, { Component } from 'react';
import './styles/base.css';
import './styles/index.css';

export default class App extends React.Component {
    state = {
        list: JSON.parse(localStorage.getItem('todu-list')) || [
            {
                id: 1,
                task: '学习React',
                isDone: false,
                edit: false
            },
            {
                id: 2,
                task: '学习Vue',
                isDone: true,
                edit: false
            },
            {
                id: 3,
                task: '学习Angular',
                isDone: false,
                edit: false
            },
        ],
        type: JSON.parse(localStorage.getItem('todu-type')) || 'all'
    }
    // 更新选中状态
    handleUpdata = (id) => {
        const list = this.state.list.map(item => ({
            ...item,
            isDone: item.id === id ? !item.isDone : item.isDone
            // map里面用点语法，可能会改变原始数组 https://blog.csdn.net/weixin_33826268/article/details/91444116
            // if (item.id === id) { 
            //     item.isDone = !item.isDone 
            // }
            // return item
        }))

        this.setState({ list })
    }
    // 删除
    handledel = (id) => {
        const list = this.state.list.filter(item => item.id !== id)
        this.setState({ list })
    }
    // 点谁谁有边框
    handleToggleType = (type) => {
        this.setState({ type })
    }
    // 清空属于已做完的数据
    handleClear = () => {
        this.setState({ list: this.state.list.filter(item => item.isDone !== true) })
    }
    // 新增
    addList = (value) => {
        this.setState({
            list: [
                {
                    id: Date.now(),
                    task: value,
                    isDone: false,
                    edit: false
                }, ...this.state.list]
        })
    }
    // 全选
    handleChangeAll = (isAll) => {
        this.setState({
            list: this.state.list.map(item => {
                return {
                    ...item, isDone: !isAll
                }
            })
        })
    }
    // 双击显现
    doubleClick = (id) => {
        // console.log(id);
        // const list = [...this.state.list]
        // list.map(item => {
        //     if (item.id === id) { item.edit = true }
        //     return true
        // })
        const index = this.state.list.findIndex(item => item.id === id)
        const list = [...this.state.list]
        list[index].edit = true
        this.setState({ list })
        // 聚焦
        setTimeout(() => {
            console.log(document.getElementById(list[index].task));
            document.getElementById(list[index].task).focus();
        }, 100)
    }
    // 失焦，关闭
    inputBlur = (id) => {
        const list = [...this.state.list]
        list.map(item => {
            if (item.id === id) { item.edit = false }
            return true
        })
        this.setState({ list })
    }
    // 修改
    editList = (e, id) => {
        const index = this.state.list.findIndex(item => item.id === id)
        const list = [...this.state.list]
        list[index].task = e.target.value
        this.setState({ list })
    }
    render() {
        const { list, type } = this.state
        const showList = list.filter(item => {
            if (type === 'active') return item.isDone === true
            if (type === 'completed') return item.isDone !== true
            return true
        })
        let count = list.filter(item => item.isDone !== true).length
        return (
            <section className="todoapp">
                {/* 头部 */}
                <Header addList={this.addList}></Header>
                {/* 主体 */}
                <Main doubleClick={this.doubleClick} editList={this.editList} inputBlur={this.inputBlur} handleChangeAll={this.handleChangeAll} handledel={this.handledel} handleUpdata={this.handleUpdata} list={showList}></Main>
                {/* 底部 */}
                <Footer count={count} handleClear={this.handleClear} type={type} handleToggleType={this.handleToggleType}></Footer>
            </section>
        );
    }
    // 在componentDidUpdate中监听数据变化
    componentDidUpdate() {
        localStorage.setItem('todu-list', JSON.stringify(this.state.list))
        localStorage.setItem('todu-type', JSON.stringify(this.state.type))
    }

}
export class Header extends Component {
    state = {
        task: ''
    }
    // 修改
    haneleChange = (task) => {
        this.setState({ task })
    }
    handleKeyDown = (e) => {
        // console.log(e);
        // 新增
        if (e.keyCode === 13) {
            if (!this.state.task.trim()) return alert('目标不能为空喔')
            this.props.addList(this.state.task)
            // 清空
            this.setState({ task: '' })
        }
        // Esc清空
        if (e.keyCode === 27) {
            // 清空
            this.setState({ task: '' })
        }
    }
    render() {
        return (
            <header className="header">
                <h1>todos</h1>
                <input value={this.state.task} onKeyDown={this.handleKeyDown} onChange={(e) => this.haneleChange(e.target.value)} className="new-todo" placeholder="需要做什么" autoFocus />
            </header>
        )
    }
}
export class Main extends Component {
    render() {
        const { list, handleUpdata, handledel, handleChangeAll, doubleClick, inputBlur, editList } = this.props
        // 小选影响全选
        const isAll = list.length ? list.every((item) => item.isDone) : false;
        return (
            <section className="main">
                <input id="toggle-all" className="toggle-all" type="checkbox" onChange={() => handleChangeAll(isAll)} checked={isAll} />
                <label htmlFor="toggle-all">全选</label>
                <ul className="todo-list">
                    {list.map(item => {
                        return (
                            <li onDoubleClick={() => doubleClick(item.id)} className={item.isDone ? "completed" : ''} key={item.id}>
                                <div className="view">
                                    <input className="toggle" type="checkbox" checked={item.isDone} onChange={() => handleUpdata(item.id)} />
                                    <label>{item.task}</label>
                                    <button className="destroy" onClick={() => handledel(item.id)} ></button>
                                </div>
                                <input onBlur={() => inputBlur(item.id)} type="text" id={item.task} className={item.edit ? 'editList' : 'isShow'} onChange={(e) => editList(e, item.id)} value={item.task} />
                            </li>
                        )
                    })}
                </ul>
            </section>
        )
    }
}
export class Footer extends Component {
    render() {
        const { handleToggleType, type, handleClear, count } = this.props
        return (
            <footer className="footer">
                <span className="todo-count">
                    <strong>{count}</strong> 剩余
                </span>
                <ul className="filters">
                    <li>
                        <a onClick={() => handleToggleType('all')} className={type === 'all' ? "all selected" : 'all'} href="#/">
                            全部
                        </a>
                    </li>
                    <li>
                        <a onClick={() => handleToggleType('active')} className={type === 'active' ? "active selected" : 'active'} href="#/active">
                            未完成
                        </a>
                    </li>
                    <li>
                        <a onClick={() => handleToggleType('completed')} className={type === 'completed' ? "completed selected" : 'completed'} href="#/completed">
                            已完成
                        </a>
                    </li>
                </ul>
                <button onClick={handleClear} className="clear-completed">清除已完成</button>
            </footer>
        )
    }
}
